package com.apes.fn.scm.lossSale;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderPayMethod;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.ReflectUtil;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = LossSaleAdjustPayment.CONST_TABLE_NAME)
public class LossSaleAdjustPayment extends Model {
    public final static String CONST_TABLE_NAME = "Loss_Sale_Adjust_Payment";

    @Id
    @Column(name = "id", nullable = false, length = 24)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "定损流程单据调整", padding = 5, prefix = "DT%(company)%(yy)%(month)", useDateRange = true)
    @Comment("调整单号")
    private String id;

    @Comment("定损单号")
    @Column(name = "loss_Quotation_Id", length = 30)
    private String lossQuotationId;

    @Comment("零售单号")
    @Column(name = "retail_id", length = 30)
    private String retailId;

    @Comment("定损门店公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("定损门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @Comment("订单备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUID; //审核

    @Comment("审批日期")
    @Column(name = "date_approve")
    private Date dateApprove;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId; //删除人

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;    // 删除日期

    @Comment("sent:创建;approve:审核;delete:删除")
    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";  // sent:创建;approve:审核;delete:删除

    @OneToMany(mappedBy = "saleAdjust", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<LossSaleAdjustPayMethod> paymentMethodSet = new HashSet(); // 付款方式明细

    public Set<LossSaleAdjustPayMethod> getPaymentMethodSet() {
        if (paymentMethodSet == null || paymentMethodSet.isEmpty()) return new HashSet<>();
        for (LossSaleAdjustPayMethod item : paymentMethodSet) {
            item.setSaleAdjust(this);
        }
        return paymentMethodSet;
    }

    public void setPaymentMethodSet(Set<LossSaleAdjustPayMethod> paymentMethodSet) {
        this.paymentMethodSet = paymentMethodSet;
    }

    @Transient
    private Set<RetailOrderPayMethod> retailOrderPayMethods;

    public Set<RetailOrderPayMethod> getRetailOrderPayMethods() {
        if (StringUtils.isEmpty(this.retailId) || "return".equals(this.state)) return new HashSet<>();

        RetailOrder retailOrder = SpringManager.getBean(RetailOrderRepository.class).findOne(this.retailId);

        Set<RetailOrderPayMethod> retailPayMethods = retailOrder.getPaymentMethodSet().stream()
                .map(retailOrderPayMethod -> {
                    RetailOrderPayMethod newPayMethod = new RetailOrderPayMethod();
                    ReflectUtil.copy(retailOrderPayMethod, newPayMethod, "amount", "note", "accountNumber", "bankAccount", "customer", "paymentMethodType");
                    return newPayMethod;
                }).collect(Collectors.toSet());

        return retailPayMethods;
    }

    @Transient
    private Map retailIdTemp;

    public Map getRetailIdTemp(){
        Map map = new HashMap<>();
        map.put("ID",this.retailId);
        return map;
    }

}
